using B.S.XZYData.Api.Wrter.Application.Command.ZSH;
using B.S.XZYData.Domain.ZSH;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.XZYData.Api.Wrter.Application.Handler.ZSH
{
	/// <summary>
	/// 编辑不良品项处理器
	/// </summary>
	public class UpdateDefectiveHandler : IRequestHandler<UpdateDefectiveCommand, ApiResult<int>>
	{
		private readonly IBaseRepository<Defective> _repo;

		public UpdateDefectiveHandler(IBaseRepository<Defective> repo)
		{
			_repo = repo;
		}

		public async Task<ApiResult<int>> Handle(UpdateDefectiveCommand request, CancellationToken cancellationToken)
		{
            var res = new ApiResult<int>();
            var entity = await _repo.GetValue(request.Id);
			if (entity == null)
			{
				res.Code = ApiEnum.Fail;
				res.Msg = "记录不存在";
				return await Task.FromResult(res);
			}

			// 编号/名称去重（排除自己）
			var exists = _repo.GetAll().Any(x => x.Id != request.Id && !x.IsDeleted && (x.DefectiveCode == request.DefectiveCode || x.DefectiveName == request.DefectiveName));
			if (exists)
			{
				res.Code = ApiEnum.Fail;
				res.Msg = "不良品项编号或名称已存在";
				return await Task.FromResult(res);
			}

			entity.DefectiveCode = request.DefectiveCode;
			entity.DefectiveName = request.DefectiveName;
			entity.AttachmentPath = request.AttachmentPath;
			entity.ImagePath = request.ImagePath;
			entity.ModifierId = request.ModifierId;
			entity.ModifyTime = System.DateTime.Now;

			var rows = await _repo.UpdateAsync(entity);
			res.Code = rows > 0 ? ApiEnum.Success : ApiEnum.Fail;
			res.Msg = rows > 0 ? "编辑成功" : "编辑失败";
			res.Data = rows;
			return res;
		}
	}
}


